//replace all the images with local one
'use strict';
var fs = require("fs");
var urls = fs.readFileSync(__dirname + "/mock_urls", "utf-8").split('\r\n');
var gen = require('./gen');
var tools = require('./tools');
module.exports = {

    summary: function () {
        return "mock server is running...";
    },


    replaceServerResDataAsync: function (req, res, serverResData, callback) {

        var mock_rules_list = fs.readFileSync(__dirname + "/mock_fields", "utf-8").split('\r\n');
		for (var i=0; i<mock_rules_list.length;i++ )
		{
			var mock_rules = JSON.parse(mock_rules_list[i]);
			 console.log('mock_rule is:' + mock_rules);
        if (/json/i.test(res.headers['content-type']) && serverResData.toString() != '') {
            try {
                var mockResData = JSON.parse(serverResData.toString('utf-8')),
                    global_mock_flag = false;
            } catch (e) {
                console.log('原始数据解析时错误，直接返回');
                callback(serverResData)
            }
            // 进入这里的，满足以下几个条件：
            // 1.肯定有规则，不是global的就是api的，或者两者都有
            // 2.原始response肯定是json，并且不为空

            // 只要global的规则不为空，就首先进行global的mock
            if (!tools.isEmpty(mock_rules.global)) {
                console.log('指定了规则，有全局规则，进行全局mock');
                // record_data(req, serverResData)
                mockResData = gen.gen_mock(mockResData, mock_rules.global)
                global_mock_flag = true
            }

            if (!tools.isEmpty(mock_rules.api)) {
                // 指定了api
                var find_flag = false,
                    api_index;
                for (api_index in mock_rules.api) {
                    console.log(api_index)
                    if (req.url.indexOf(api_index) != -1) {
                        console.log('命中api')
                        console.log(req.url)
                        find_flag = true
                        break
                    }
                }
                if (find_flag) {
                    console.log('指定的api命中!!返回mock数据')
                    if (!global_mock_flag) {
                        //record_data(req, serverResData)
                    }
                    mockResData = gen.gen_mock(mockResData, mock_rules.api[api_index])
                } else {
                    console.log('指定的api没有命中，返回原始数据')
					if (i==mock_rules_list.length-1)
					{
						callback(serverResData)
					}
						
					continue
                }
            } else {
                console.log('api 未指定');
            }
            callback(JSON.stringify(mockResData))
			break
        } else {
            callback(serverResData)
        }
		}
        //var mock_rules = JSON.parse(fs.readFileSync(__dirname + "/mock_fields", "utf-8").split('\r\n')[0])
       
    },

    //mark if use local response
    shouldUseLocalResponse: function (req, reqBody) {
        urls = fs.readFileSync(__dirname + "/mock_urls", "utf-8").split('\r\n');
        console.log('**********');
        console.log(urls);
        console.log('req is:' + req.url);
        for (var i = 0, l = urls.length; i < l; i++) {
            console.log('urls[i]' + urls[i]);
            var api = urls[i].replace(/(^\s*)|(\s*$)/g, "").split(':') [0];
            if (api == "") {
                return false;
            }
            var urlPattern = new RegExp(api);
            if (urlPattern.test(req.url)) {
                console.log('match----------');
                return true;
            }
        }
        return false;
    },

    dealLocalResponse: function (req, reqBody, callback) {
        console.log('deal local response...');
        var request = require('request-json');
// callback(200, {"content-type":"application/json"}, fs.readFileSync("F:/python/apiMock/response/"+"homeworklist_isgroup") );
        var client = request.createClient('http://127.0.0.1:5000');
        for (var i = 0, l = urls.length; i < l; i++) {
            var lines = urls[i].replace(/(^\s*)|(\s*$)/g, "")
            var api = lines.split(':') [0];
            var filename = lines.split(':') [1];
            var urlPattern = new RegExp(api);

            if (urlPattern.test(req.url)) {
                callback(200, {"content-type": "application/json"}, fs.readFileSync(__dirname + "/response/" + filename));
            }
        }
    }

};

